package com.bc.bczbweb.common;

import com.bc.bcmodel.consts.GlobalSettings;
import com.bc.bcmodel.domain.T_Mnguser_infoModel;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.util.CookieUtils;
import com.bc.commoncore.util.JsonUtil;
import com.bc.commoncore.util.SpringBeanHelper;
import com.bc.commoncore.util.StringUtils;
import com.bc.bccore.redis.RedisService;
import com.bc.bcmodel.ShopLoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class UserContext {

	protected static final Logger LOGGER = LoggerFactory.getLogger(UserContext.class);
	private final static RedisService redisService;
	static {
		redisService = SpringBeanHelper.getCustomBeanByType(RedisService.class);
	}
	private UserContext(T_Mnguser_infoModel req){
		this.loginInfo=req;
	}
	T_Mnguser_infoModel loginInfo;
	public static boolean checkIsLogin(){
		return getCurrentContext()!=null;
	}
	public static boolean checkIsAllow(int userId,String url){
		return true;
	}

	public T_Mnguser_infoModel getLoginInfo(){
		return this.loginInfo;
	}
	
	public static  UserContext getCurrentContext() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String decryptValue =""; 
		 
			String cookieValue =CookieUtils.getCookie(request, GlobalSettings.MANAGE_COOKIENAME);
			if(cookieValue==null||cookieValue.trim().isEmpty()){
				LOGGER.debug(GlobalSettings.MANAGE_COOKIENAME+"=空");
				return null;
			}
			try {
				LOGGER.debug("解密cookieValue="+cookieValue);
//				cookieValue=cookieValue.replace(" ", "+");
				decryptValue = AES.aesDecrypt(cookieValue.trim());
			} catch (Exception e) {
				LOGGER.error("cookieValue="+cookieValue+"解密失败");
				return null;
			}
 
		if (decryptValue != null&&!decryptValue.isEmpty()) {
			return getContext(decryptValue);
		}
		return null;
	}
	private static UserContext getContext(String decryptValue){
		try {
			T_Mnguser_infoModel model = JsonUtil.str2obj(decryptValue,T_Mnguser_infoModel.class);
			return new UserContext(model);
		} catch (Exception e) {
			LOGGER.debug("根据解密后的cookie解析用户信息时失败:"+e.getMessage()+StringUtils.getStackTrace(e));
			return null;
		}
	}
}
